<!DOCTYPE html>
<html>
   <head>
         <meta charset="utf-8">
         <meta http-equiv="X-UA-Compatible" content="IE=edge">
         <title>我的生活</title>
         <meta name="viewport" content="initial-scale=1, maximum-scale=1">
         <link rel="shortcut icon" href="/favicon.ico">
         <meta name="apple-mobile-web-app-capable" content="yes">
         <meta name="apple-mobile-web-app-status-bar-style" content="black">
    
         <link rel="stylesheet" href="/h5/dist/css/light7.min.css">
         <link rel="stylesheet" href="/h5/dist/css/light7-swiper.min.css">
         <link rel="stylesheet" href="/h5/css/validate.css">
         <link rel="stylesheet" href="/h5/styles/style.css">
         <link rel="stylesheet" href="/B-JUI/themes/css/FA/css/font-awesome.css">
         <link rel="stylesheet" type="text/css" href="/h5/css/fonts/iconfont.css">
         <link rel="stylesheet" type="text/css" href="/h5/css/styles.css">
  </head>

  <body>
    <div class="page page-current" id='indexPage'>
      <a class="icon icon-me pull-right open-panel"></a>
      <header class="bar bar-nav">
      <a class="button button-link button-nav pull-right open-popover back" data-popover=".popover-links" href="#">
      <span class="icon icon-home" style="color: #fff"></span>
      </a>
      <a class='title' style="color:#fff;cursor: pointer;"><i class="fa fa-leaf"></i><span class="pl-8">NB-loT数据平台</span></a>
      </header>
      <div class="content pull-to-refresh-content" data-ptr-distance="55">
          <div class="pull-to-refresh-layer">
            <div class="preloader"></div>
            <div class="pull-to-refresh-arrow"></div>
          </div>
          <div class="content-block">
            <ul class="h5statistical-number"></ul>
          </div>
         <div class="panel panel-default row-panel">
         </div>
      </div>
    </div>
 
    <!-- 导航消息栏 -->
    <div class="popover popover-links" style="display: none; top: 114px; left: 5px;">
      <div class="popover-angle on-top" style="left: 52px;"></div>
      <div class="popover-inner">
        <div class="list-block">
          <ul>
            <li><a href="/h5/changePasswordPage" class="list-button item-link"><i class="fa fa-gear" style="margin-left: -1rem;padding-right: .3rem"></i><font style="vertical-align: inherit;"><font style="vertical-align: inherit;"> 修改密码</font></font></a></li>
            <li><a href="/h5/login" class="list-button item-link external"><i class="fa fa-sign-out" style="margin-left: -2.6rem;padding-right: .5rem"></i><font style="vertical-align: inherit;"><font style="vertical-align: inherit;">退出</font></font></a></li>
            <li><a href="#" class="list-button item-link close-popover"><font style="vertical-align: inherit;"><font style="vertical-align: inherit;">关闭</font></font></a></li>
          </ul>
        </div>
     </div>
    </div>
    <!-- 导航栏-->
    <script type='text/javascript' src='/h5/js/common.js' charset='utf-8'></script>
    <script type='text/javascript' src='/h5/js/general.js' charset='utf-8'></script>
    <script type='text/javascript' src='/h5/dist/js/jquery.min.js' charset='utf-8'></script>
    <script type='text/javascript' src='/h5/js/jquery.form.js' charset='utf-8'></script>
    <script type='text/javascript' src='/h5/dist/js/light7.min.js' charset='utf-8'></script>
    <script type='text/javascript' src='/h5/dist/js/light7-swiper.min.js' charset='utf-8'></script>
    <script type='text/javascript' src='/h5/js/public.js' charset='utf-8'></script>
    <script type='text/javascript' src='/h5/js/jquery-mvalidate.js' charset='utf-8'></script>
    <script src="/javascripts/des.js"></script>

    <script type="text/javascript">

         var ids=[],totalRow=0,allIds=[],businessDelArr=[],appDelArr=[],t;
    $(document).ready(function(){
        
        get_img_code();

        ajax_statistics();

        $(document).on("pageReinit","#indexPage", function(e, pageId, $page) {
          ajax_statistics();

        });

        $(document).on("pageInit","#login", function(e, pageId, $page) {
        
            window.location.href='/h5/index';
        });
         
        $(document).on('refresh', '.pull-to-refresh-content',function(e) {
            setTimeout(function() {
                 ajax_statistics();
                $.pullToRefreshDone('.pull-to-refresh-content');
            }, 2000);
        });


      $(document).on("pageInit", "#deviceList", function(e, pageId, $page) {    //设备列表
              var index=2,lastIndex=0,totalRow=0;
              var loading = false;
              var maxItems = 100;
              var itemsPerLoad = 20;
              addDeviceItems(1, 10,'');
              get_device_list();

        $(document).on('infinite', '.infinite-scroll',function() {
            // 如果正在加载，则退出
            if (loading) return;
            // 设置flag
            loading = true;
            setTimeout(function() {
              lastIndex=$('.device-list li').length;
                loading = false;
                if (lastIndex %10 >0 || totalRow == lastIndex) { //有余数和总数结束
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    $('.infinite-scroll-preloader').remove();
                    return;
                }
                 if($('#checkboxBtn').is(':visible')){
                    addDeviceItems(index++, 10,'','checkbox');
                }else if($('#radioBtn').is(':visible')){
                    addDeviceItems(index++, 10,'','radio');
                }else{
                    addDeviceItems(index++, 10,'');
                }

               
            }, 1000);
        });
         
        $('.device_search').click(function() {  //设备搜索
          if($('#checkboxBtn').is(':visible')){   //多选按钮可见状态
               $('.device-list').empty();
             addDeviceItems(1, 10,$('.device-sn').val(),$('#device-bussinessname option:selected').val(),'checkbox');
          }else if($('#radioBtn').is(':visible')){ //单选按钮可见状态
               $('.device-list').empty();
           addDeviceItems(1, 10,$('.device-sn').val(),$('#device-bussinessname option:selected').val(),'radio');
          }else{
               $('.device-list').empty();
            addDeviceItems(1, 10,$('.device-sn').val(),$('#device-bussinessname option:selected').val()); //既不多选也不单选
          }
        });

      

           $(document).on('click', '.device-edit-btn',function () {           //私协点击编辑
                      if(deviceDelArr.length==0){
                          $.toast("请选择设备");                             //弹窗显示
                      }else{
                          $('#device-content').removeClass('mb30');
                          $('#footerEditdevice').css('display','none');
                          $('.device-list .item-content #radioBtn').css('display','none');
                      }
        });

           function get_device_list(){
            $.ajax({
                url:"/devices/businesslist",
                type:"post",
                dataType:"json",
                success:function(data){
                        $.each(data,function(i,item){
                            $("#device-bussinessname").append("<option class='bussinessNameOption' value="+item.name+">"+item.name+"</option>");
                         })
                },
                statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
                }
            })
          }

        $(document).on('refresh', '.pull-to-refresh-content',function(e) {
          setTimeout(function() {
              $('.device-list').empty();
                addDeviceItems(1, 10,$('.device-sn').val(),$('#device-bussinessname option:selected').val());
                // done
                $.pullToRefreshDone('.pull-to-refresh-content');
            }, 2000);
        });

         $(document).on('click', '.device-del-btn',function () {
                      if(ids.length==0){
                        $.toast("请选择设备");
                      }else{
                        $.confirm('确认要删除设备?', 
                          function () {
                            $.ajax({
                              type:'post',
                              url:'/devices/del',
                              data:{'ids':ids},
                              dataType:'json',
                              success:function(json){
                                if(json.statusCode=='200'){
                                  $.toast(json.message);
                                  $('.device-list').empty();
                                 addDeviceItems(1, 10,$('.device-sn').val(),$('#device-bussinessname option:selected').val());; 
                                  $('#footerDeldevice').css('display','none');
                                }
                              },
                         statusCode : {
                            503: function(xhr, ajaxOptions, thrownError) {
                               $.toast('数据加载超时');
                                 }
                               }
                            })
                          },
                          function () {
                            $('#device-content').removeClass('mb30');
                            $('#footerDeldevice').css('display','none');
                            $('.device-list .item-content label').css('display','none');
                          }
                        );
                      }
        });
      });
     
       $(document).on("pageReinit","#deviceList", function(e, pageId, $page) {
         addDeviceItems(1, 10,'');

      });  


           //设备详情
      $(document).on("pageInit", "#deviceDetail", function(e, pageId, $page){  //设备详情
    
        var sn = $('#sn').text();
        var index=2,lastIndex=0,totalRow=0;
        var loading = false;

        $("#datetime-picker").calendar({
          monthNames:['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'],
          dateFormat:'yyyy-mm',
        });

        $("#configtime-picker").calendar({
          monthNames:['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'],
          dateFormat:'yyyy-mm',
        });

        $(document).on("click", ".searchbar input", function(e) {
          var $input = $(e.target);
          $input.parents(".searchbar").addClass("searchbar-active");
        });
     
        addDataItems(1, 10,'');

        $(document).on('infinite', '.infinite-scroll',function() {
            // 如果正在加载，则退出
            if (loading) return;
            // 设置flag
            loading = true;
            setTimeout(function() {
              lastIndex=$('.devicedataDetail .card').length;
                loading = false;
                if (lastIndex %10 >0) { //有余数和总数结束
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    $('.infinite-scroll-preloader').remove();
                    return;
                }
                addDataItems(index++, 10,'');
            }, 1000);
        });
          
        $('.deviceData_search').click(function() { //设备搜索
           $('.devicedataDetail').empty();
           $('.noneinfo').empty();//清除上次没数据的提醒信息
          addDataItems(1, 10,$('.deviceData-createdate').val());
        });

        function addDataItems(pageCurrent, pageSize, deviceSn) {
          $.ajax({
            url:'/devices/datalist',
            type:'post',
            // data:{pageCurrent:pageCurrent, pageSize:pageSize,name:deviceSn},
            data:{"name":sn,createdate:deviceSn},
            dataType:'json',
            success:function(json){
             
           $('.noneinfo').empty();//清除上次没数据的提醒信息

                if(json.list.length==0){
                  $('.devicedataDetail').append('<p class="noneinfo">没有当前月份的数据!</p>');
                   $('.infinite-scroll-preloader').remove();
                }
              totalRow=json.totalRow;
               deviceDataJson(json);
              },
                statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
                }
           });
        }

        function deviceDataJson(json){
          $('.devicedataDetail').deviceData(json);
        }

        $(document).on('refresh', '.pull-to-refresh-content',function(e) {
          setTimeout(function() {
          $('.devicedataDetail').empty();
          addDataItems(1, 10,$('.deviceData-createdate').val());
          $.pullToRefreshDone('.pull-to-refresh-content');
          }, 2000);
        });

         addDeviceInfoItems();

        function addDeviceInfoItems() {
          $.ajax({
            url:'/devices/getDeviceInfo',
            type:'post',
            data:{"sn":sn},
            dataType:'json',
            success:function(json){
              devicedetailJson(json);
            },
                statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
                }
          });
        }

        function devicedetailJson(json){
            $('.deviceDetail').devicedetail(json.data);
        }

        $(document).on('refresh', '.pull-to-refresh-content',function(e) {
           setTimeout(function() {
             // $('.deviceDetail').empty();
             addDeviceInfoItems();
             $.pullToRefreshDone('.pull-to-refresh-content');
         }, 2000);
        });
 
        addConfigItems(1, 10);//设备配置

        $(document).on('infinite', '.infinite-scroll',function() {
            // 如果正在加载，则退出
            if (loading) return;
            // 设置flag
            loading = true;
            setTimeout(function() {
              lastIndex=$('.deviceConfigDetail .card').length;
                loading = false;
                if (lastIndex %10 >0|| totalRow == lastIndex) { //有余数和总数结束
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    $('.infinite-scroll-preloader').remove();
                    return;
                }
                addConfigItems(index++, 10);
            }, 1000);
        });
          
        $('.deviceConfig_search').click(function() {//设备搜索
           $('.deviceConfigDetail').empty();
           $('.noneinfo').empty();//清除上次没数据的提醒信息
          addConfigItems(1, 10,$('.deviceConfig-createdate').val());
        });

        function addConfigItems(pageCurrent, pageSize, deviceSn) {
          $.ajax({
            url:'/devices/configList',
            type:'post',
            data:{"name":sn,createdate:deviceSn},
            dataType:'json',
            success:function(json){
               $('.noneinfo').empty();
                if(json.list.length==0){
                  $('.deviceConfigDetail').append('<p class="noneinfo">没有当前月份的数据!</p>');
                   $('.infinite-scroll-preloader').remove();
                }
              totalRow=json.totalRow;
               deviceConfigJson(json);
              },
                statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
                }
          });
        }
           
        function deviceConfigJson(json){
             $('.deviceConfigDetail').deviceConfig(json);
        }

        $(document).on('refresh', '.pull-to-refresh-content',function(e) {
           setTimeout(function() {
             // $('.deviceConfigDetail').empty();
             addConfigItems(1, 10,$('.deviceConfig-createdate').val());
             $.pullToRefreshDone('.pull-to-refresh-content');
         }, 2000);
        });
      }); 

       //设备添加
       //私有协议添加
      $(document).on("pageInit", "#deviceAdd", function(e, pageId, $page){
       var sn =$('#deviceSn').val();
       var id=$('#user-id').val();
          if(sn){
              $('.device-title').text('编辑设备');
              $("#device-isadd").val(1);
              get_business_list(id);
              
          }else{
              $('.device-title').text('添加设备');
              get_business_list();
          }
          get_netway_list();
         function get_business_list(id){
        $.ajax({
            url:"/devices/getBusinessList",
            type:"post",
            data:{'userid':id},
            dataType:"json",
            success:function(data){
                if(data.statusCode=='200'){
                    $.each(data.list,function(i,item){
                        $("#device-businessid").append('<option value="'+item.id+'" >'+item.name+'</option>')
                    })
                    if(sn){
                      console.log(sn);
                        getDeviceInfo(sn);
                    }
                }
            },
            statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
            }
        })
      } 

      function get_netway_list(){
           $.ajax({
              url:"/devices/getNetwayList",
              type:"post",
              dataType:"json",
              success:function(data){
                  if(data.statusCode=='200'){
                      $.each(data.list,function(i,item){
                          $("#device-netwayid").append('<option value="'+item.id+'" >'+item.name+'</option>')
                      })
                  }
              },
                statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
                }
          })
      }

      function getDeviceInfo(sn){
          $.ajax({
              url:"/devices/getDeviceInfo",
              type:"post",
              data:{"sn":sn},
              dataType:"JSON",
              success:function(json){
                $("#device-sn").val(json.data.sn).attr('readonly','readonly');
                $("#device-name").val(json.data.name);
                $("#device-businessid").val(json.data.businessid); 
                $("#device-imsi").val(json.data.imsi);
                $("#device-imei").val(json.data.imei);
                $("#device-coapid").val(json.data.coapdeviceid)
                json.data.coapdeviceid ?  $("#device-coapid").parents('.form-group').css('display','block') :'';
                $("#device-coappsk").val(json.data.coappsk);
                json.data.coappsk ?  $("#device-coappsk").parents('.form-group').css('display','block') :'';
                $("#device-location").val(json.data.location);
                $("#device-coordinate").val(json.data.coordinate);
                $("#device-netwayid").val( json.data.netwayid); 
                $("#device-info-textarea").val(json.data.info);
              },
                statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
                }
          })
      }
         
          function  luhn(value) {
                console.log('1111111111')
               console.log(value)
              
                var length  = value.length,
                    mul     = 0,
                    prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
                    sum     = 0;
                while (length--) {
                    sum += prodArr[mul][parseInt(value.charAt(length), 10)];
                    mul ^= 1;
                }
                console.log((sum % 10 === 0 && sum > 0));
                return (sum % 10 === 0 && sum > 0);
          }
          $.mvalidateExtend({
                imsi:{
                    required : false,   
                    pattern : /^(4600[0,1,2,3,5,6,7]|46020)\d{10}$/,
                    each:function(){
                       
                    },
                    descriptions:{
                        pattern : '<div class="field-invalidmsg">IMSI输入错误了</div>',
                    }
                },
                location:{
                    required : false,   
                    pattern : /^[\u4e00-\u9fa5_a-zA-Z0-9-]+$/,
                    each:function(){
                       
                    },
                    descriptions:{
                        pattern : '<div class="field-invalidmsg">位置只能由字母、数字和中文组成</div>',
                    }
                },
                coordinate:{
                    required : false,   
                    pattern : /^\d+(\.\d+)\,\d+(\.\d+)$/,
                    each:function(){
                       
                    },
                    descriptions:{
                        pattern : '<div class="field-invalidmsg">坐标输入错误</div>',
                    }
                }
              });
         $("#device-add-form").mvalidate({
            type:1,
            onKeyup:true,
            sendForm:true,
            firstInvalidFocus:false,
            valid:function(event,options){
               e.preventDefault();
                 $("#device-add-form").ajaxSubmit(function(data){
                    if(data.statusCode==200){
                      console.log(data);
                      $.toast(data.message);
                      $.router.back('/h5/device/list');
                    }else{
                      $.toast(data.message);
                    }
                 })
                 event.preventDefault();
            },
            invalid:function(event, status, options){
                //点击提交按钮时,表单未通过验证触发函数
            },
            eachField:function(event,status,options){
                //点击提交按钮时,表单每个输入域触发这个函数 this 执向当前表单输入域，是jquery对象
            },
            eachValidField:function(val){},
            eachInvalidField:function(event, status, options){},
            conditional:{
                sn:function(val){
                  var patt =/^[a-zA-Z0-9]{0,12}$/
                  return patt.test(val);
                },
                name:function(val){
                  var patt =/^[\u4e00-\u9fa5_.a-zA-Z0-9-]{2,30}$/
                   return patt.test(val);
                },
                imei:function(val){
                  console.log(val);
                   // var patt = 
                    switch (true) {
                case /^\d{15}$/.test(val):
                case /^\d{2}-\d{6}-\d{6}-\d{1}$/.test(val):
                case /^\d{2}\s\d{6}\s\d{6}\s\d{1}$/.test(val):
                    val = val.replace(/[^0-9]/g, '');
                    return luhn(val);

                case /^\d{14}$/.test(val):
                case /^\d{16}$/.test(val):
                case /^\d{2}-\d{6}-\d{6}(|-\d{2})$/.test(val):
                case /^\d{2}\s\d{6}\s\d{6}(|\s\d{2})$/.test(val):
                    return true;

                default:
                    return false;
                }},
                info:function(val){
                  var patt =/^.{0,200}$/
                   return patt.test(val);
              }
            },
            descriptions:{
              sn:{
                  required : '请输入设备SN',
                  conditional:'SN只能由字母、数字组成,长度不得超过12个字符'
                },
              name:{
                required : '请输入设备名称',
                conditional:'设备名称只能由字母、数字、中文、点、下划线点和减号组成,长度必须2到30之间'
                },
              imei:{
                required : '请输入imei',
                conditional:'请输入正确格式imei'
                },
              info:{
                conditional:'设备描述不得超过200个字符'
                }
            }
          });
        
      })


      $(document).on("pageInit", "#protocolList", function(e, pageId, $page) {    //私有协议列表
              var index=2,lastIndex=0,totalRow=0;
              var loading = false;
              var maxItems = 100;
              var itemsPerLoad = 20;
              addProtocolItems(1, 10,'');

        $(document).on('infinite', '.infinite-scroll',function() {
            // 如果正在加载，则退出
            if (loading) return;
            // 设置flag
            loading = true;
            setTimeout(function() {
              lastIndex=$('.protocol-list li').length;
                loading = false;
                if (lastIndex %10 >0 || totalRow == lastIndex) { //有余数和总数结束
                    $.detachInfiniteScroll($('.infinite-scroll'));
                    $('.infinite-scroll-preloader').remove();
                    return;
                }
                if($('#checkboxBtn').is(':visible')){
                    addProtocolItems(index++, 10,'','checkbox');
                }else if($('#radioBtn').is(':visible')){
                    addProtocolItems(index++, 10,'','radio');
                }else{
                    addProtocolItems(index++, 10,'');
                }
            }, 1000);
        });
         
        $('.protocol_search').click(function() {  //设备搜索
          if($('#checkboxBtn').is(':visible')){   //多选按钮可见状态
              $('.protocol-list').empty();
              addProtocolItems(1, 10,$('.protocol-name').val(),'checkbox');
          }else if($('#radioBtn').is(':visible')){ //单选按钮可见状态
              $('.protocol-list').empty();
              addProtocolItems(1, 10,$('.protocol-name').val(),'radio');
          }else{
              $('.protocol-list').empty();
              addProtocolItems(1, 10,$('.protocol-name').val()); //既不多选也不单选
          }
        });

        $(document).on('refresh', '.pull-to-refresh-content',function(e) {  //列表刷新
          setTimeout(function() {
              // $('.protocol-list').empty();
                addProtocolItems(1, 10,$('.protocol-name').val());
                // done
                $.pullToRefreshDone('.pull-to-refresh-content');
            }, 2000);
        });

        $(document).on('click', '.protocol-edit-btn',function () {           //私协点击编辑
                      if(protocolDelArr.length==0){
                          $.toast("请选择私有协议");                             //弹窗显示
                      }else{
                          $('#protocol-content').removeClass('mb30');
                          $('#footerEditprotocol').css('display','none');
                          $('.protocol-list .item-content #radioBtn').css('display','none');
                      }
        });

        $(document).on('click', '.protocol-del-btn',function () {

                      if(ids.length==0){
                        $.toast("请选择私有协议");
                      }else{
                        $.confirm('确认要删除私有协议?', 
                          function () {
                            $.ajax({
                              type:'post',
                              url:'/userProtocol/del',
                              data:{'id':ids},
                              dataType:'json',
                              success:function(json){
                                if(json.statusCode=='200'){
                                  $.toast(json.message);
                                  $('.protocol-list').empty();
                                 addProtocolItems(1, 10,$('.protocol-name').val());; 
                                  $('#footerDelprotocol').css('display','none');
                                }
                              }
                            })
                          },
                          function () {
                            $('#protocol-content').removeClass('mb30');
                            $('#footerDelprotocol').css('display','none');
                            $('.protocol-list .item-content label').css('display','none');
                          }
                        );
                      }
        });
      }); 

        $(document).on("pageReinit","#protocolList", function(e, pageId, $page) {
         addProtocolItems(1, 10,'');
      });   

        
         //私有协议详情
      $(document).on("pageInit", "#protocolDetail", function(e, pageId, $page){ 
  
        addProtocolDetailItems(1, 10,'');

        function addProtocolDetailItems(pageCurrent, pageSize, deviceSn) {
          $.ajax({
            url:'/userProtocol/getUserProtocol',
            type:'post',
            // data:{pageCurrent:pageCurrent, pageSize:pageSize,name:deviceSn},
            data:{"id":$('#protocolId').text()},
            dataType:'json',
            success:function(json){
                $('.protocol-name').text(json.data.name)
                $('.protocol-memo').text(json.data.memo)
              
           
              $.each(json.data.ktvlist,function(i,item){
               
                 $('tbody').append("<tr class='protocoltr'>"+
                        "<td class='protocolTd protocol-kname'>"+item.kname+"</td>"+
                        "<td class='protocolTd protocol-t'>"+type_onversion(item.t)+"</td>"+
                        "<td class='protocolTd protocol-k'>"+item.k+"</td>"+
                        "<td class='protocolTd protocol-t_description'>"+item.t_description+"</td>"+
                    "</tr>");
              })
            }
          });
        }
        // $(document).on('refresh', '.pull-to-refresh-content',function(e) {  //列表刷新
        //   setTimeout(function() {
        //         // addProtocolDetailItems(1, 10,'');
        //         $.pullToRefreshDone('.pull-to-refresh-content');
        //     }, 2000);
        // });
      }); 
          
      
       //私有协议添加
      $(document).on("pageInit", "#protocolAdd", function(e, pageId, $page){
          
          var addId=$('#protocol-id').val();
         get_ktv_list();

          if(addId){  //编辑获取id对应用户协议
              $('.protocol-title').text('编辑私有协议');
              get_userProtocol(addId);
          }else{
              $('.protocol-title').text('添加私有协议');
          }

          function get_ktv_list(){
            $.ajax({
                url:"/userProtocol/getKtvList",
                type:"post",
                dataType:"json",
                success:function(data){
                    if(data.statusCode=='200' && data.list !=''){
                        objKtv=data.list;
                        $.each(data.list,function(i,item){
                            $("#userproto-kValue").append("<option value="+item.id+">"+item.name+"</option>");
                        })
                    }
                }
            })
          }

          function get_userProtocol(id){    //编辑时id对应用户协议
             $.ajax({
                url:'/userProtocol/getUserProtocol',
                type:'post',
                data:{'id':id},
                dataType:'json',
                success:function(json){

               $("#protocol-name").val(json.data.name);
               $("#protocol-memo").val(json.data.memo);
               var data=json.data.ktvlist.sort(sortNumber);
               $.each(data,function(i,item){
                    var t=type_onversion(item.t);
                    add_field(item.kid,item.kname,item.k,t,item.t_description)
                   })
                }
            })
          }
         
          function sortNumber(a,b)
          {
          return a.seq - b.seq
          }
         
          $("#protocol-add-form").mvalidate({
            type:1,
            onKeyup:true,
            sendForm:true,
            firstInvalidFocus:false,
            valid:function(event,options){
               e.preventDefault();
            var ktvlist=[];
            $(".protocol-list-ul li").each(function(index){
                var id=$(this).find('.kid').text();
                var t=$(this).find('.t_description').text();
                var kValues=$(this).find('.kValues').text();

                ktvlist.push('{"kid":'+id+',"kValues":'+kValues+',"t_description":"'+t+'","seq":'+index+'}')
            })
            $("#userproto-ktvlist").val('['+ktvlist+']');
                 $("#protocol-add-form").ajaxSubmit(function(data){
                    if(data.statusCode==200){
                      $.toast(data.message);
                      $.router.back('/h5/protocol/list');
                    }
                 })
                 event.preventDefault();
            },
            invalid:function(event, status, options){
                //点击提交按钮时,表单未通过验证触发函数
            },
            eachField:function(event,status,options){
                //点击提交按钮时,表单每个输入域触发这个函数 this 执向当前表单输入域，是jquery对象
            },
            eachValidField:function(val){},
            eachInvalidField:function(event, status, options){},
            conditional:{
                name:function(val){
                  var patt =/^[\u4e00-\u9fa5_a-zA-Z0-9-]{2,30}$/
                  return patt.test(val);
                },
                company:function(val){
                  var patt =/^.{0,15}$/
                   return patt.test(val);
                },
                memo:function(val){
                  var patt =/^.{0,200}$/
                   return patt.test(val);
              }
            },
            descriptions:{
                name:{
                    required : '请输入用户协议名称',
                    conditional:'业务名称只能由字母、数字、中文、下划线和减号组成,长度必须2到30之间'
                },
                company:{
                  conditional:'长度不得超过15个字节'
              },
                memo:{
                  conditional:'私有协议不得超过200个字符'
              }
            }
          });
      })


      $(document).on("pageInit", "#modify-password", function(e, pageId, $page) {
          $().ready(function() {
              $.mvalidateExtend({
                password:{
                    required : true,   
                    pattern : /^[A-Za-z0-9]{8,}$/,
                    each:function(){
                       
                    },
                    descriptions:{
                        required : '<div class="field-invalidmsg" style="color:red">请输入新密码</div>',
                        pattern : '<div class="field-invalidmsg" style="color:red">长度不少于8位</div>',
                        valid : '<div class="field-validmsg"><strong><span style="color:#6bb20a" class="icon icon-check"></span></strong></div>'
                    }
                }
              });
              $("#passwordForm").mvalidate({
                type:2,
                onKeyup:true,
                sendForm:true,
                firstInvalidFocus:true,
                valid:function(event,options){
                    //点击提交按钮时,表单通过验证触发函数
                    alert("密码修改成功！");
                    window.location.href="/login";
                    event.preventDefault();
                },
                invalid:function(event, status, options){
                    //点击提交按钮时,表单未通过验证触发函数
                },
                eachField:function(event,status,options){
                    //点击提交按钮时,表单每个输入域触发这个函数 this 执向当前表单输入域，是jquery对象
                },
                eachValidField:function(val){},
                eachInvalidField:function(event, status, options){},
                conditional:{
                    pwd2:function(val,options){
                        $("#confirmpwd2").trigger("keyup."+options.namespace);
                        return true;
                    },
                    confirmpwd2:function(val){
                        var flag;
                        return (val==$("#pwd2").val()) ? true :false; 
                    },
                },
                descriptions:{
                    username:{
                        required : '<div class="field-invalidmsg" style="color:red">请输入用户名</div>',
                        valid : '<div class="field-validmsg"><strong><span style="color:#6bb20a" class="icon icon-check"></span></strong></div>'
                    },
                    // password:{
                    //      required : '<div class="field-invalidmsg">请输入密码</div>',
                    //      conditional : '<div class="field-validmsg">验证通过</div>',
                    //      valid : '<div class="field-validmsg"><strong><span style="color:#6bb20a" class="icon icon-check"></span></strong></div>'
                    // },
                    confirmpassword:{
                        required : '<div class="field-invalidmsg" style="color:red">请再次输入密码</div>',
                        conditional : '<div class="field-invalidmsg" style="color:red">两次密码不一样</div>',
                        valid : '<div class="field-validmsg"><strong><span style="color:#6bb20a" class="icon icon-check"></span></strong></div>'
                    }
                  }

              });
          });
      });
    }) //第一个预加载结束
  
     
      $(document).on("pageInit", "#businessList", function(e, pageId, $page) {
            var index=2,lastIndex=0;
            var loading = false;
            var maxItems = 100;
            var itemsPerLoad = 20;
            addBusinessItems(1, 10,'');
            $(document).on('infinite', '.infinite-scroll',function() {
                // 如果正在加载，则退出
                if (loading) return;
                // 设置flag
                loading = true;
                setTimeout(function() {
                  lastIndex=$('.business-list li').length;
                    loading = false;
                    if (lastIndex %10 >0 || totalRow == lastIndex) {
                        $.detachInfiniteScroll($('.infinite-scroll'));
                        $('.infinite-scroll-preloader').remove();
                        return;
                    }
                    if($('#checkboxBtn').is(':visible')){
                        addBusinessItems(index++, 10,'','checkbox');
                    }else if($('#radioBtn').is(':visible')){
                        addBusinessItems(index++, 10,'','radio');
                    }else{
                        addBusinessItems(index++, 10,'');
                    }
                    
                }, 1000);
            });
            $('.business_search').click(function() {
              businessDelArr=[],ids=[];
              if($('#checkboxBtn').is(':visible')){
                  $('.business-list').empty();
                  addBusinessItems(1, 10,$('.business-name').val(),'checkbox');
              }else if($('#radioBtn').is(':visible')){
                  $('.business-list').empty();
                  addBusinessItems(1, 10,$('.business-name').val(),'radio');
              }else{
                  $('.business-list').empty();
                  addBusinessItems(1, 10,$('.business-name').val());
              }
              
            });
           
            $(document).on('click', '.business-del-btn',function () {
              if(ids.length==0){
                $.toast("请选择业务");
              }else{
                $.confirm('确认要删除业务?', 
                  function () {
                    $.ajax({
                      type:'post',
                      url:'/business/del',
                      data:{'id':ids},
                      dataType:'json',
                      success:function(json){
                        if(json.statusCode=='200'){
                          $.toast(json.message);
                          $('.business-list').empty();
                          addBusinessItems(1, 10,$('.business-name').val());
                          $('#footerDelBusiness').css('display','none');
                          $('#business-content').removeClass('mb30');
                        }
                      },
                      statusCode : {
                        503: function(xhr, ajaxOptions, thrownError) {
                            $.toast('数据加载超时');
                        }
                      }
                    })
                  },
                  function () {
                    $('#business-content').removeClass('mb30');
                    $('#footerDelBusiness').css('display','none');
                    $('.business-list .item-content label').css('display','none');
                  }
                );
              }
                
            });
            $(document).on('click', '.business-edit-btn',function () {
              if(businessDelArr.length==0){
                  $.toast("请选择业务");
              }else{
                  $('#business-content').removeClass('mb30');
                  $('#footerEditBusiness').css('display','none');
                  $('.business-list .item-content #radioBtn').css('display','none');
              }
 
            });
            $(document).on('refresh', '.pull-to-refresh-content',function(e) {
                setTimeout(function() {
                    addBusinessItems(1, 10,$('.business-name').val());
                    $.pullToRefreshDone('.pull-to-refresh-content');
                }, 2000);
            });
      });
      $(document).on("pageReinit","#businessList", function(e, pageId, $page) {
        addBusinessItems(1, 10,'');
      });
      $(document).on("pageInit", "#businessDetail", function(e, pageId, $page){
        get_business_data();
        function get_business_data(){
            $.ajax({
              type:'post',
              url:'/business/getBusiness',
              data:{'id':$('#businessId').text()},
              dataType:'json',
              success:function(json){
                $('.business-name').text(json.data.name)
                $('.business-proto').text(json.data.protocolName)
                $('.business-product').text(json.data.productname)
                $('.business-app').text(json.data.app)
                // $('.business-url').text(json.data.pushurl)
                $('.business-memo').text(json.data.memo)
              },
              statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
              }
            }) 
        }
        
        $(document).on('refresh', '.pull-to-refresh-content',function(e) {
            setTimeout(function() {
                get_business_data();
                $.pullToRefreshDone('.pull-to-refresh-content');
            }, 2000);
        }); 
      });

      $(document).on("pageInit", "#businessAdd", function(e, pageId, $page){

        var addId=$('#business-id').val();
        if(addId){
            $('.business-title').text('编辑业务');
            get_proto_list(addId);
            get_app_list(addId);
            get_business(addId);
        }else{
           $('.business-title').text('添加业务');
            get_proto_list();
            get_app_list();
            $('#business-key').val(uuid()).attr('readonly',true);
        }
        get_product();
        function get_proto_list(id){
            $.ajax({
              url:"/business/getProtocolList",
              type:"post",
              data:{'id':id},
              dataType:"json",
              success:function(data){
                  if(data.statusCode=='200' && data.list !=''){
                      $.each(data.list,function(i,item){
                        $("#business-protocolid").append("<option value="+item.id+">"+item.name+"</option>");
                      })
                  }
              },
              statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
              }
            })
        }
        function get_app_list(id){
            $.ajax({
              url:"/business/getAppList",
              type:"post",
              data:{'id':id},
              dataType:"json",
              success:function(data){
                  var appArr=['']
                  if(data.statusCode=='200' && data.list !=''){
                      $.each(data.list,function(i,item){
                          $("#business-app").append("<option value="+item.id+">"+item.name+"</option>");
                      })
                  }
              },
              statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
              }
            })
        }
        function get_product(){
            $.ajax({
              url:'/product/getAllProduct',
              type:'post',
              dataType:'json',
              success:function(data){
                  var productArr=[];
                  if(data.statusCode=='200' && data.list !=''){
                      $.each(data.list,function(i,item){
                        $("#business-productid").append("<option value="+item.id+">"+item.name+"</option>");
                      })
                  }
              },
              statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
              }
            })
        }
        function get_business(id){
              $.ajax({
                url:'/business/getBusiness',
                type:'post',
                data:{'id':id},
                dataType:'json',
                success:function(json){
                   $("#business-name").val(json.data.name);
                   $("#business-memo").val(json.data.memo);
                   $('#business-protocolid').val(json.data.protocolid);
                   $('#business-key').val(json.data.key).attr('readonly',true);
                   $("#business-app").val(json.data.appid);
                   $('#business-productid').val(json.data.productid);
                },
                statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
                }
              })
        }
        
        $("#business-add-form").mvalidate({
          type:1,
          onKeyup:true,
          sendForm:true,
          firstInvalidFocus:false,
          valid:function(event,options){
               $("#business-add-form").ajaxSubmit(function(data){
                  if(data.statusCode==200){
                    $.toast(data.message);
                    $.router.back('/h5/business/list');
                  }
               })
               event.preventDefault();
          },
          invalid:function(event, status, options){
              //点击提交按钮时,表单未通过验证触发函数
          },
          eachField:function(event,status,options){
              //点击提交按钮时,表单每个输入域触发这个函数 this 执向当前表单输入域，是jquery对象
          },
          eachValidField:function(val){},
          eachInvalidField:function(event, status, options){},
          conditional:{
              name:function(val){
                var patt =/^[\u4e00-\u9fa5_a-zA-Z0-9-]{2,30}$/
                return patt.test(val);
              },
              memo:function(val){
                  var patt =/^.{0,200}$/
                   return patt.test(val);
              }
          },
          descriptions:{
              name:{
                  required : '请输入业务名称',
                  conditional:'业务名称只能由字母、数字、中文、下划线和减号组成,长度必须2到30之间'
              },
              productid:{
                   required : '请选择产品名称'
              },
              memo:{
                  conditional:'业务描述不得超过200个字符'
              }
          }
        });
      })

      $(document).on("pageInit", "#appList", function(e, pageId, $page) {
              var index=2,lastIndex=0;
              var loading = false;
              var maxItems = 100;
              var itemsPerLoad = 20;
              addAppItems(1, 10,'');
              $(document).on('infinite', '.infinite-scroll',function() {
                  // 如果正在加载，则退出
                  if (loading) return;
                  // 设置flag
                  loading = true;
                  setTimeout(function() {
                    lastIndex=$('.app-list li').length;
                      loading = false;
                      if (lastIndex %10 >0 || totalRow == lastIndex) {
                          $.detachInfiniteScroll($('.infinite-scroll'));
                          $('.infinite-scroll-preloader').remove();
                          return;
                      }
                      if($('#checkboxBtn').is(':visible')){
                          addAppItems(index++, 10,'','checkbox');
                      }else if($('#radioBtn').is(':visible')){
                          addAppItems(index++, 10,'','radio');
                      }else{
                          addAppItems(index++, 10,'');
                      }
                      
                  }, 1000);
              });
              $('.app_search').click(function() {
                appDelArr=[],ids=[];
                if($('#checkboxBtn').is(':visible')){
                    $('.app-list').empty();
                    addAppItems(1, 10,$('.app-name').val(),'checkbox');
                }else if($('#radioBtn').is(':visible')){
                    $('.app-list').empty();
                    addAppItems(1, 10,$('.app-name').val(),'radio');
                }else{
                    $('.app-list').empty();
                    addAppItems(1, 10,$('.app-name').val());
                }
                
              });
              
              $(document).on('click', '.app-del-btn',function () {
                if(ids.length==0){
                  $.toast("请选择应用");
                }else{
                  $.confirm('确认要删除应用?', 
                    function () {
                      $.ajax({
                        type:'post',
                        url:'/app/del',
                        data:{'id':ids},
                        dataType:'json',
                        success:function(json){
                          if(json.statusCode=='200'){
                            $.toast(json.message);
                            $('.app-list').empty();
                            addAppItems(1, 10,$('.app-name').val());
                            $('#footerDelApp').css('display','none');
                            $('#app-content').removeClass('mb30');
                          }
                        },
                        statusCode : {
                                503: function(xhr, ajaxOptions, thrownError) {
                                    $.toast('数据加载超时');
                                }
                        }
                      })
                    },
                    function () {
                      $('#app-content').removeClass('mb30');
                      $('#footerDelApp').css('display','none');
                      $('.app-list .item-content label').css('display','none');
                    }
                  );
                }
                  
              });
              $(document).on('click', '.app-edit-btn',function () {
                if(appDelArr.length==0){
                    $.toast("请选择业务");
                }else{
                    $('#app-content').removeClass('mb30');
                    $('#footerEditApp').css('display','none');
                    $('.app-list .item-content #radioBtn').css('display','none');
                }
   
              });
              $(document).on('refresh', '.pull-to-refresh-content',function(e) {
                  t = setTimeout(function() {
                      addAppItems(1, 10,$('.app-name').val());
                      $.pullToRefreshDone('.pull-to-refresh-content');
                  }, 2000);
              });
      });
      $(document).on("pageReinit","#appList", function(e, pageId, $page) {
        addAppItems(1, 10,'');
      });
      $(document).on("pageInit", "#appDetail", function(e, pageId, $page){
        get_app_data();
        function get_app_data(){
            $.ajax({
              type:'post',
              url:'/app/getApp',
              data:{'id':$('#appId').text()},
              dataType:'json',
              success:function(json){
                $('.app-name').text(json.data.appname);
                $('.app-url').text(json.data.url);
                $('.app-token').text(json.data.token);
                $('.app-memo').text(json.data.appmemo);
              },
              statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
              }
            }) 
        }
        
        $(document).on('refresh', '.pull-to-refresh-content',function(e) {
            setTimeout(function() {
                get_app_data();
                $.pullToRefreshDone('.pull-to-refresh-content');
            }, 2000);
        }); 
      });

      $(document).on("pageInit", "#appAdd", function(e, pageId, $page){
        
        var addId=$('#app-id').val();
        if(addId){
          $('.app-title').text('编辑应用');
          get_app(addId);
        }else{
            $('.app-title').text('添加应用');
            $('#app-token').val(uuid()).attr('readonly',true);
        }
        function get_app(id){  
             $.ajax({
                url:"/app/getApp",
                type:"post",
                dataType:"json",
                data:{"id":id},
                success:function(data){  //id发送成功向页面发送信息
                  $("#app-url").val(data.data.url);
                  $("#app-token").val(data.data.token).attr('readonly',true);
                  $("#app-name").val(data.data.appname);
                  $("#app-appmemo").val(data.data.appmemo);
                },
                statusCode : {
                    503: function(xhr, ajaxOptions, thrownError) {
                        $.toast('数据加载超时');
                    }
                }
            });
         }
              
        $("#app-add-form").mvalidate({
          type:1,
          onKeyup:true,
          sendForm:true,
          firstInvalidFocus:false,
          valid:function(event,options){
                $.showPreloader('正在测试url地址')
                setTimeout(function () {
                    $.ajax({
                       url:"/app/testAddress",
                       type:"POST",
                       data:{'url':$('#app-url').val()},
                       dataType:"json",
                        success:function(data){   //获取该网址是否可用的返回码
                          $.hidePreloader();
                          if(data.statusCode=="200"){
                              $("#app-add-form").ajaxSubmit(function(json){
                                if(json.statusCode==200){
                                  $.toast(json.message);
                                  $.router.back('/h5/app/list');
                                }
                              })
                          }else{
                             $.toast(data.message);
                          }
                        },
                        statusCode : {
                                503: function(xhr, ajaxOptions, thrownError) {
                                    $.toast('数据加载超时');
                                }
                        }
                    });
                }, 2000);
               event.preventDefault();
          },
          invalid:function(event, status, options){
              //点击提交按钮时,表单未通过验证触发函数
          },
          eachField:function(event,status,options){
              //点击提交按钮时,表单每个输入域触发这个函数 this 执向当前表单输入域，是jquery对象
          },
          eachValidField:function(val){},
          eachInvalidField:function(event, status, options){},
          conditional:{
              name:function(val){
                var patt =/^[\u4e00-\u9fa5_a-zA-Z0-9-]{2,30}$/
                return patt.test(val);
              },
              url:function(val){
                // var patt =/^[\u4e00-\u9fa5_a-zA-Z0-9-]{2,30}$/
                urlExp  = new RegExp(
                          "^" +
                          // protocol identifier
                          "(?:(?:http)://)" +
                          // user:pass authentication
                          "(?:\\S+(?::\\S*)?@)?" +
                          "(?:" +
                          // IP address dotted notation octets
                          // excludes loopback network 0.0.0.0
                          // excludes reserved space >= 224.0.0.0
                          // excludes network & broadcast addresses
                          // (first & last IP address of each class)
                          "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
                          "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
                          "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
                          "|" +
                          // host name
                          "(?:(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9]+)" +
                          // domain name
                          "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9])*" +
                          // TLD identifier
                          "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
                          // Allow intranet sites (no TLD) if `allowLocal` is true
                           '?' +
                          ")" +
                          // port number
                          "(?::\\d{2,5})?" +
                          // resource path
                          "(?:/[^\\s]*)?" +
                          "$", "i"
                      );
                return urlExp.test(val);
              },
              memo:function(val){
                  var patt =/^.{0,200}$/
                   return patt.test(val);
              }
          },
          descriptions:{
              name:{
                  required : '请输入应用名称',
                  conditional:'业务名称只能由字母、数字、中文、下划线和减号组成,长度必须2到30之间'
              },
              url:{
                   required : '请填写网址',
                   conditional:'请输入http://格式网址'
              },
              memo:{
                  conditional:'业务描述不得超过200个字符'
              }
          }
        });
      })


      
    </script>
  </body>
</html>
